package edu.tum.cs.mesh.language.linking;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.diagnostics.IDiagnosticConsumer;
import org.eclipse.xtext.linking.lazy.LazyLinker;

import edu.tum.cs.mesh.language.mesh.Function;
import edu.tum.cs.mesh.language.mesh.MeshFactory;

public class MeshLinker extends LazyLinker {

	private final Map<EBuildInFunctions, Function> functionCache = new HashMap<>();

	@Override
	protected void beforeModelLinked(EObject model,
			IDiagnosticConsumer diagnosticsConsumer) {
		for (EBuildInFunctions f : EBuildInFunctions.values()) {
			addFunction(model, f);
		}

		super.beforeModelLinked(model, diagnosticsConsumer);
	}

	private void addFunction(EObject model, EBuildInFunctions f) {
		Function function = functionCache.get(f);
		if (function == null) {
			function = MeshFactory.eINSTANCE.createFunction();
			function.setName(f.name());
			functionCache.put(f, function);
		}
		if (!model.eResource().getContents().contains(function)) {
			model.eResource().getContents().add(function);
		}
	}
}
